<?php

namespace App\Api\Controllers\v1_0;

use App\Http\Controllers\ApiController;
use App\User;
use Illuminate\Http\Request;
use JWTAuth;

class AuthController extends ApiController
{
    /**
     * 注册用户
     * @param Request $request
     * @return mixed
     */
    public function register(Request $request)
    {
        $credentials = $request->only('email', 'password');
        $validate = \Validator::make($credentials, [
            'email' => 'required|unique:users,email',
            'password' => 'required'
        ], [
            'email.required' => '邮箱不能为空',
            'password.required' => '密码不能为空',
            'email.unique' => '邮箱已存在'
        ]);
        if ($validate->fails()) {
            return message(false, '数据验证不通过', $validate->errors(), 401, 401);
        }

        $credentials['password'] = bcrypt($credentials['password']);

        if ($user = User::create($credentials)) {
            $token = JWTAuth::fromUser($user);
            return message(true, '注册成功', ['token' => $token]);
        } else {
            return message(false, '注册失败');
        }
    }
    /**
     * 登录账号
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        $validate = \Validator::make($credentials, [
            'email' => 'required',
            'password' => 'required'
        ], [
            'email.required' => '邮箱不能为空',
            'password.required' => '密码不能为空'
        ]);
        if ($validate->fails()) {
            return message(false, '数据验证不通过', $validate->errors(), 401, 401);
        }
        $user = User::where('email', $credentials['email'])->first();
        if ($user) {
            $is_check = \Hash::check($request->input('password'), $user->password);
            if ($is_check) {
                $token = JWTAuth::fromUser($user);
                return message(true, '登录成功', ['token' => $token]);
            }
        }
        return message(false, '账号或密码错误');
    }
}
